<?php

namespace app\api\controller;

use app\common\controller\Frontend;
use app\common\model\User;
use app\common\model\Product;
use app\common\model\Cart;
use app\common\library\MpPay;
use think\facade\Db;
use think\Exception;

class Shop extends Frontend
{
    protected array $noNeedLogin =['index'];
    public function index(){
        $product = Product::where('status',1)->select();
        $this->success('',$product);
    }
    
    public function cart(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $data['user_id'] = $this->auth->id;
            $data['openid'] = User::where('id',$this->auth->id)->value('openid');
            $data['goods_id'] = $data['id'];
            $data['goods_title'] = '地平线洗车充值卡'.intval($data['price']).'元'.($data['gift']?'赠送'.$data['gift'].'元':'');
            $data['out_trade_no'] = date('ymd', time()) . mt_rand(1000, 9999) . substr(time(), '3', '8');
            $data['create_time'] = time();
            $data['update_time'] = time();
            unset($data['id']);
            $res = Cart::create($data);
            $this->success('添加成功',$res);
        }
    }

    public function payment(){
        if($this->request->isPost()){
            $order = $this->request->post();
            $payment = MpPay::precreate($order);
            $cart = Cart::where('id',$order['id'])->find();
            $cart->status = 2;
            $cart->save();
            $this->success('',$payment);
        }
    }
}